"""
Case Type   : 系统内部使用工具
Case Name   : gs_ctl start指定-t的值过小，启动备机
Create At   : 2021/01/15
Owner       : opentestcase015
Description :
    1.关闭正在运行的备机
    2.指定-t的值为1启动备机，10s后查看备机
    3.查看集群状态
Expect      :
    1.关闭正在运行的备机成功
    2.启动失败，10s后备机状态正常
    3.查看集群状态成功
History     :
    Modified by lopentestcase027 2023/1/9: 优化用例步骤格式及一主两备判断方式
"""

import unittest
import time
import os
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

LOG = Logger()
primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class LogicalReplication(unittest.TestCase):
    def setUp(self):
        LOG.info(f'--------{os.path.basename(__file__)} start--------')
        self.constant = Constant()
        self.PrimaryNode = Node('PrimaryDbUser')
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.user_node = Node('Standby1DbUser')

    def test_system_internal_tools(self):
        LOG.info('--------step1:关闭正在运行的备机   expect:关闭成功--------')
        excute_cmd = f'''
                    source {macro.DB_ENV_PATH};
                    gs_ctl stop -D {macro.DB_INSTANCE_PATH} 
                '''
        LOG.info(excute_cmd)
        msg = self.user_node.sh(excute_cmd).result()
        LOG.info(msg)
        self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, msg)

        LOG.info('--------step2:指定-t的值为1启动备机，10s后查看备机  '
                 'expect:启动失败，10s后备机状态正常--------')
        excute_cmd = f'''
                    source {macro.DB_ENV_PATH};
                    gs_ctl start -D {macro.DB_INSTANCE_PATH} -M standby -t 1; 
                        '''
        LOG.info(excute_cmd)
        msg = self.user_node.sh(excute_cmd).result()
        LOG.info(msg)
        self.assertIn(self.constant.could_not_start_sever, msg)
        time.sleep(10)

        LOG.info('--------step3:查看备机状态   expect:状态正常--------')
        status = self.sh_primary.get_db_cluster_status(param='detail')
        self.assertTrue(len(status.splitlines()) >= 10)
        self.assertIn('Standby Normal', status.splitlines()[-2])

    def tearDown(self):
        LOG.info('--------step4:启动备机   expect:成功--------')
        excute_cmd = f'''
                        source {macro.DB_ENV_PATH};
                        gs_ctl start -D {macro.DB_INSTANCE_PATH} -M standby; 
                    '''
        LOG.info(excute_cmd)
        msg = self.user_node.sh(excute_cmd).result()
        LOG.info(msg)
        status = self.sh_primary.get_db_cluster_status(param='detail')
        self.assertTrue(len(status.splitlines()) >= 10)
        self.assertIn('Standby Normal', status.splitlines()[-2])
        LOG.info(f'--------{os.path.basename(__file__)} end--------')
